const { StringUtils, FileUtils } = require('./Utils')
const path = require('path')

class RepoGenerator {
  constructor(repo) {
    this.repo = repo;
  }

  async saveFileByIndex(index, linesCount, fileSizeKB) {
    const filename = FileUtils.getHashFileNameByIndex(index);
    const fullFileName = path.join(this.repo.repoPath, filename);      

    const fileContent = StringUtils.randomLines(fileSizeKB, linesCount);
    FileUtils.saveFile(fullFileName, fileContent);
    console.log('Creating file: ' + fullFileName);
    return index;
  }

  async saveFiles({index, indexArr=[], indexRange=[0, 0]}, linesCount=100, fileSizeKB=[100, 1024]) {
    if (index != undefined && indexArr.indexOf(index) == -1) {
      indexArr.push(index);      
    }
    for (let index = indexRange[0]; index < indexRange[1]; index++) {
      if (indexArr.indexOf(index) == -1) {
        indexArr.push(index);
      }
    }

    for (let index of indexArr) {
      if (fileSizeKB instanceof Array) {
        const fileSize = Math.floor(Math.random() * (fileSizeKB[1] - fileSizeKB[0]) + fileSizeKB[0]);
        this.saveFileByIndex(index, linesCount, fileSize);
      } else {
        this.saveFileByIndex(index, linesCount, fileSizeKB);
      }
    }
    return indexArr
  }
}

class DiffRepoGenerator extends RepoGenerator {
  constructor(repo) {
    super(repo)
  }

  async create() {
    await this.repo.init();
    await this.saveFiles({indexRange: [0, 10]}, 1000, 1024);
    await this.repo.status();
    await this.repo.add();
    await this.repo.commit();
  }
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  // CommonJS 模块导出
  module.exports = {
    DiffRepoGenerator,
  };
} else if (typeof define === 'function' && define.amd) {
  // ES6 模块导出
  define([], DiffRepoGenerator);
} else if (typeof exports === 'object') {
  // Node/CommonJS
  module.exports = {
    DiffRepoGenerator,
  };
} else {
  // Exported as a string, for Closure Compiler in advanced mode.
  var globalVar = (function() { return this; })();
  globalVar.DiffRepoGenerator = DiffRepoGenerator;
}
